<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket</title>

</head>
<body>
<input type="text" id="nickname"/>
<button onclick="conectWebSocket()">连接websocket</button>
<button onclick="closeWebSocket()">断开websocket</button>
<hr />
<br />
消息： <input type="text" id="text">
频道号：<input type="text" id="toUser">
<button onclick="send()">发送消息</button>
<div id="message"></div>


<script>
    document.body.style.backgroundColor="pink"
    var websocket=null;
    function conectWebSocket(){
        var nickname=document.getElementById("nickname").value;
        if (nickname==null||nickname==''){
            alert("请输入昵称");
            return;
        }

        if ('WebSocket' in window){
            websocket =new WebSocket("ws://localhost:8099/websocket/"+nickname);
        }else {
            alert("not support websocket")
        }
        console.log(websocket)
        websocket.onerror=function(){
            setMessageInnerHtml("error");
        }
        websocket.onopenr=function(event){
            setMessageInnerHtml("Loc MSG: 成功建立连接")
        }
        websocket.onmessage=function(event){
            setMessageInnerHtml(event.data)
        }
        websocket.onclose=function(){
            setMessageInnerHtml("Log MSG: 关闭连接");
        }
    }
    function setMessageInnerHtml(message){
        document.getElementById("message").innerHTML=document.getElementById("message").innerHTML+message +'<br />';
    }
    window.onbeforeunload=function (ev) {
        websocket.close()
    }
    function  closeWebSocket(){
        websocket.close()
    }
    function send(){
        var message=document.getElementById("text").value;
        var toUser=document.getElementById("toUser").value;
        var socketMsg={
            msg:message,
            toUser:toUser
        };
        if (toUser==''){
            //群聊
            socketMsg.type=0;
        } else {
            //单聊
            socketMsg.type=1;
        }


        websocket.send(JSON.stringify(socketMsg));
    }
    function abd() {

    }

</script>

</body>
</html>